#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#define PORT 8080

int main() {
    struct sockaddr_in serv_addr;
    int sock = 0, valread;
    char *hello = "Hello from client";
    char buffer[1024] = {0};

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        printf("\n Socket creation error \n");
        return -1;
    }

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);

    if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
        printf("\nInvalid address / Address not supported \n");
        return -1;
    }

    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        printf("\nConnection Failed \n");
        return -1;
    }

    // 循环发送信息
    while(1) {
        printf("Enter message : ");
        fgets(buffer, 1024, stdin);
        send(sock, buffer, strlen(buffer), 0);
        printf("Hello message sent\n");
        
        // 接收服务端回传的信息
        valread = read(sock, buffer, 1024);
        printf("Message from server: %s\n", buffer);
        
        // 检查用户是否想要退出循环
        if (strcmp(buffer, "quit") == 0) {
            break;
        }
    }

    close(sock);
    return 0;
}
